<template>
  <div class="trading-container">
    <el-row :gutter="20">
      <!-- 市场概览 -->
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>市场概览</span>
              <div class="data-source-controls">
                <span class="last-updated">最后更新: {{ lastUpdated }}</span>
                <el-select v-model="selectedDataSource" placeholder="选择数据源" size="small" style="margin-right: 10px;">
                  <el-option
                    v-for="item in dataSources"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                <el-button type="primary" size="small" @click="fetchDataBySource" :loading="isLoading">刷新</el-button>
                <el-switch
                  v-model="autoRefresh"
                  active-text="自动刷新"
                  inactive-text="手动刷新"
                  @change="toggleAutoRefresh"
                />
              </div>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="6" v-for="(item, index) in marketOverview" :key="index">
              <div class="market-item" :class="{ 'up': item.change > 0, 'down': item.change < 0 }">
                <div class="market-name">{{ item.name }}</div>
                <div class="market-price">{{ item.price }}</div>
                <div class="market-change">
                  <span>{{ item.change > 0 ? '+' : '' }}{{ item.change }}%</span>
                  <el-icon v-if="item.change > 0"><CaretTop /></el-icon>
                  <el-icon v-else-if="item.change < 0"><CaretBottom /></el-icon>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 多数据源比较 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>多数据源价格比较</span>
              <div>
                <el-tag type="success">每分钟自动更新所有数据源</el-tag>
                <el-button type="primary" size="small" @click="fetchAllDataSources" :loading="isLoading" style="margin-left: 10px;">立即刷新全部</el-button>
              </div>
            </div>
          </template>
          <el-table :data="comparisonData" style="width: 100%" border>
            <el-table-column prop="symbol" label="交易对" width="120"></el-table-column>
            <el-table-column label="CoinGecko">
              <template #default="scope">
                <div class="price-cell">
                  <div>{{ scope.row.coingecko.price || '加载中...' }}</div>
                  <div :class="{ 'up': scope.row.coingecko.change > 0, 'down': scope.row.coingecko.change < 0 }">
                    {{ scope.row.coingecko.change > 0 ? '+' : '' }}{{ scope.row.coingecko.change }}%
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="Binance">
              <template #default="scope">
                <div class="price-cell">
                  <div>{{ scope.row.binance.price || '加载中...' }}</div>
                  <div :class="{ 'up': scope.row.binance.change > 0, 'down': scope.row.binance.change < 0 }">
                    {{ scope.row.binance.change > 0 ? '+' : '' }}{{ scope.row.binance.change }}%
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="CryptoCompare">
              <template #default="scope">
                <div class="price-cell">
                  <div>{{ scope.row.cryptocompare.price || '加载中...' }}</div>
                  <div :class="{ 'up': scope.row.cryptocompare.change > 0, 'down': scope.row.cryptocompare.change < 0 }">
                    {{ scope.row.cryptocompare.change > 0 ? '+' : '' }}{{ scope.row.cryptocompare.change }}%
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="价格差异">
              <template #default="scope">
                <div class="price-diff">
                  <el-tooltip content="最高价与最低价之间的差异百分比" placement="top">
                    <span :class="{ 'warning': scope.row.priceDiff > 1 }">
                      {{ scope.row.priceDiff.toFixed(2) }}%
                    </span>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- Binance 交易图表 - 单独占一行 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>Binance 交易图表</span>
              <el-select v-model="binanceSymbol" placeholder="选择交易对" size="small" @change="updateBinanceChart">
                <el-option
                  v-for="item in symbols"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value.replace('/', '')">
                </el-option>
              </el-select>
            </div>
          </template>
          <div class="chart-container">
            <webview 
              ref="binanceWebview"
              :src="`https://www.binance.com/zh-CN/trade/${binanceSymbol}?theme=dark&type=spot`"
              class="binance-webview"
              allowpopups
              allow="autoplay; fullscreen"
              webpreferences="contextIsolation=no"
            ></webview>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 交易操作和订单资产区域 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 交易操作 -->
      <el-col :span="16">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>交易操作</span>
            </div>
          </template>
          <el-form :model="tradeForm" label-width="80px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="交易类型">
                  <el-radio-group v-model="tradeForm.type">
                    <el-radio label="buy">买入</el-radio>
                    <el-radio label="sell">卖出</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="订单类型">
                  <el-select v-model="tradeForm.orderType" placeholder="请选择" style="width: 100%;">
                    <el-option label="市价单" value="market"></el-option>
                    <el-option label="限价单" value="limit"></el-option>
                    <el-option label="止损单" value="stop"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="价格">
                  <el-input v-model="tradeForm.price" type="number" :disabled="tradeForm.orderType === 'market'">
                    <template #append>USDT</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="数量">
                  <el-input v-model="tradeForm.amount" type="number">
                    <template #append>BTC</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="总额">
                  <el-input v-model="totalAmount" disabled>
                    <template #append>USDT</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button type="primary" :class="{ 'buy-btn': tradeForm.type === 'buy', 'sell-btn': tradeForm.type === 'sell' }" @click="submitTrade">
                {{ tradeForm.type === 'buy' ? '买入' : '卖出' }} {{ selectedSymbol.split('/')[0] }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 订单和资产 -->
      <el-col :span="8">
        <!-- 资产概览 -->
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>资产概览</span>
            </div>
          </template>
          <div class="asset-overview">
            <div class="asset-item">
              <div class="asset-label">总资产估值</div>
              <div class="asset-value">$25,468.32</div>
            </div>
            <el-divider></el-divider>
            <div v-for="(asset, index) in assets" :key="index" class="asset-detail">
              <span class="asset-name">{{ asset.name }}</span>
              <span class="asset-balance">{{ asset.balance }} {{ asset.symbol }}</span>
              <span class="asset-value">${{ asset.value }}</span>
            </div>
          </div>
        </el-card>

        <!-- 当前订单 -->
        <el-card class="box-card" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>当前订单</span>
            </div>
          </template>
          <el-table :data="orders" style="width: 100%" size="small">
            <el-table-column prop="symbol" label="交易对" width="80"></el-table-column>
            <el-table-column prop="type" label="类型" width="60">
              <template #default="scope">
                <el-tag :type="scope.row.type === 'buy' ? 'success' : 'danger'" size="small">
                  {{ scope.row.type === 'buy' ? '买入' : '卖出' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格"></el-table-column>
            <el-table-column prop="amount" label="数量"></el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button type="text" size="small" @click="cancelOrder(scope.row)">取消</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 交易历史 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>交易历史</span>
            </div>
          </template>
          <el-table :data="tradeHistory" style="width: 100%">
            <el-table-column prop="time" label="时间" width="180"></el-table-column>
            <el-table-column prop="symbol" label="交易对" width="100"></el-table-column>
            <el-table-column prop="type" label="类型" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.type === 'buy' ? 'success' : 'danger'">
                  {{ scope.row.type === 'buy' ? '买入' : '卖出' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格" width="120"></el-table-column>
            <el-table-column prop="amount" label="数量" width="120"></el-table-column>
            <el-table-column prop="total" label="总额" width="120"></el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'completed' ? 'success' : 'info'">
                  {{ scope.row.status === 'completed' ? '已完成' : '处理中' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 交易回测功能 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>交易策略回测</span>
              <div>
                <el-button type="primary" size="small" @click="runBacktest" :loading="isBacktesting">运行回测</el-button>
                <el-button type="success" size="small" @click="saveStrategy" :disabled="!backtestResults.length">保存策略</el-button>
                <el-button size="small" @click="loadStrategy">加载策略</el-button>
              </div>
            </div>
          </template>
          
          <el-form :model="backtestSettings" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="交易对">
                  <el-select v-model="backtestSettings.symbol" placeholder="选择交易对">
                    <el-option
                      v-for="item in symbols"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="回测周期">
                  <el-select v-model="backtestSettings.period" placeholder="选择周期">
                    <el-option label="最近7天" value="7d"></el-option>
                    <el-option label="最近30天" value="30d"></el-option>
                    <el-option label="最近90天" value="90d"></el-option>
                    <el-option label="最近1年" value="1y"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="K线周期">
                  <el-select v-model="backtestSettings.interval" placeholder="选择K线周期">
                    <el-option label="1分钟" value="1m"></el-option>
                    <el-option label="5分钟" value="5m"></el-option>
                    <el-option label="15分钟" value="15m"></el-option>
                    <el-option label="1小时" value="1h"></el-option>
                    <el-option label="4小时" value="4h"></el-option>
                    <el-option label="1天" value="1d"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="策略类型">
                  <el-select v-model="backtestSettings.strategyType" placeholder="选择策略类型">
                    <el-option label="移动平均线交叉" value="ma_cross"></el-option>
                    <el-option label="RSI策略" value="rsi"></el-option>
                    <el-option label="布林带策略" value="bollinger"></el-option>
                    <el-option label="自定义策略" value="custom"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="初始资金">
                  <el-input-number v-model="backtestSettings.initialCapital" :min="100" :step="100" :max="1000000"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="每笔交易资金">
                  <el-input-number v-model="backtestSettings.tradeAmount" :min="1" :step="1" :max="100"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            
            <!-- 策略参数 -->
            <el-row :gutter="20" v-if="backtestSettings.strategyType === 'ma_cross'">
              <el-col :span="8">
                <el-form-item label="快速MA周期">
                  <el-input-number v-model="backtestSettings.fastMAPeriod" :min="5" :step="1" :max="50"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="慢速MA周期">
                  <el-input-number v-model="backtestSettings.slowMAPeriod" :min="10" :step="1" :max="100"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20" v-if="backtestSettings.strategyType === 'rsi'">
              <el-col :span="8">
                <el-form-item label="RSI周期">
                  <el-input-number v-model="backtestSettings.rsiPeriod" :min="5" :step="1" :max="30"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="超买阈值">
                  <el-input-number v-model="backtestSettings.overbought" :min="50" :step="1" :max="90"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="超卖阈值">
                  <el-input-number v-model="backtestSettings.oversold" :min="10" :step="1" :max="50"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20" v-if="backtestSettings.strategyType === 'bollinger'">
              <el-col :span="8">
                <el-form-item label="布林带周期">
                  <el-input-number v-model="backtestSettings.bbPeriod" :min="10" :step="1" :max="50"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="标准差倍数">
                  <el-input-number v-model="backtestSettings.bbStdDev" :min="1" :step="0.1" :max="3"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20" v-if="backtestSettings.strategyType === 'custom'">
              <el-col :span="24">
                <el-form-item label="自定义策略代码">
                  <el-input 
                    v-model="backtestSettings.customStrategy" 
                    type="textarea" 
                    :rows="4" 
                    placeholder="输入您的自定义策略代码"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <!-- 风险管理 -->
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="止损比例">
                  <el-input-number v-model="backtestSettings.stopLoss" :min="0" :step="0.1" :max="20"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="止盈比例">
                  <el-input-number v-model="backtestSettings.takeProfit" :min="0" :step="0.1" :max="50"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          
          <!-- 回测结果 -->
          <div v-if="backtestResults.length" class="backtest-results">
            <el-divider></el-divider>
            <h3>回测结果摘要</h3>
            
            <el-row :gutter="20">
              <el-col :span="8">
                <el-card shadow="hover">
                  <div class="result-item">
                    <div class="result-label">总收益率</div>
                    <div class="result-value" :class="{ 'up': backtestSummary.totalReturn > 0, 'down': backtestSummary.totalReturn < 0 }">
                      {{ backtestSummary.totalReturn > 0 ? '+' : '' }}{{ backtestSummary.totalReturn.toFixed(2) }}%
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <div class="result-item">
                    <div class="result-label">年化收益率</div>
                    <div class="result-value" :class="{ 'up': backtestSummary.annualReturn > 0, 'down': backtestSummary.annualReturn < 0 }">
                      {{ backtestSummary.annualReturn > 0 ? '+' : '' }}{{ backtestSummary.annualReturn.toFixed(2) }}%
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <div class="result-item">
                    <div class="result-label">夏普比率</div>
                    <div class="result-value">{{ backtestSummary.sharpeRatio.toFixed(2) }}</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            
            <el-row :gutter="20" style="margin-top: 20px;">
              <el-col :span="8">
                <el-card shadow="hover">
                  <div class="result-item">
                    <div class="result-label">最大回撤</div>
                    <div class="result-value">{{ backtestSummary.maxDrawdown.toFixed(2) }}%</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <div class="result-item">
                    <div class="result-label">胜率</div>
                    <div class="result-value">{{ backtestSummary.winRate.toFixed(2) }}%</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <div class="result-item">
                    <div class="result-label">总交易次数</div>
                    <div class="result-value">{{ backtestSummary.totalTrades }}</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            
            <!-- 回测图表 -->
            <div class="backtest-chart-container" style="margin-top: 20px; height: 400px;">
              <div ref="backtestChart" style="width: 100%; height: 100%;"></div>
            </div>
            
            <!-- 交易记录 -->
            <el-divider></el-divider>
            <h3>交易记录</h3>
            <!-- 回测结果统计 -->
            <el-card shadow="hover" style="margin-top: 20px;">
              <template #header>
                <div class="card-header">
                  <span>回测结果统计</span>
                </div>
              </template>
              <div class="result-stats">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <div class="stat-item">
                      <div class="stat-label">总收益率</div>
                      <div class="stat-value" :class="backtestSummary.totalReturn >= 0 ? 'profit' : 'loss'">
                        {{ backtestSummary.totalReturn.toFixed(2) }}%
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="stat-item">
                      <div class="stat-label">年化收益率</div>
                      <div class="stat-value" :class="backtestSummary.annualReturn >= 0 ? 'profit' : 'loss'">
                        {{ backtestSummary.annualReturn.toFixed(2) }}%
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="stat-item">
                      <div class="stat-label">夏普比率</div>
                      <div class="stat-value">
                        {{ backtestSummary.sharpeRatio.toFixed(2) }}
                      </div>
                    </div>
                  </el-col>
                </el-row>
                <el-row :gutter="20" style="margin-top: 20px;">
                  <el-col :span="8">
                    <div class="stat-item">
                      <div class="stat-label">最大回撤</div>
                      <div class="stat-value loss">
                        {{ backtestSummary.maxDrawdown.toFixed(2) }}%
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="stat-item">
                      <div class="stat-label">胜率</div>
                      <div class="stat-value">
                        {{ backtestSummary.winRate.toFixed(2) }}%
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="stat-item">
                      <div class="stat-label">总交易次数</div>
                      <div class="stat-value">
                        {{ backtestSummary.totalTrades }}
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-card>

            <!-- 交易记录表格 -->
            <el-card shadow="hover" style="margin-top: 20px;">
              <template #header>
                <div class="card-header">
                  <span>交易记录</span>
                </div>
              </template>
              <el-table :data="backtestTrades" style="width: 100%;" stripe>
                <el-table-column prop="date" label="日期" width="120" sortable />
                <el-table-column prop="type" label="类型" width="80">
                  <template #default="scope">
                    <el-tag :type="scope.row.type === 'buy' ? 'success' : 'danger'" size="small">
                      {{ scope.row.type === 'buy' ? '买入' : '卖出' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="价格" width="120">
                  <template #default="scope">
                    ${{ scope.row.price.toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column prop="amount" label="数量" width="120" />
                <el-table-column prop="value" label="价值" width="120">
                  <template #default="scope">
                    ${{ scope.row.value.toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column prop="profit" label="盈亏" width="120" v-if="backtestTrades.some(t => t.profit !== undefined)">
                  <template #default="scope">
                    <span v-if="scope.row.profit !== undefined" 
                          :class="scope.row.profit >= 0 ? 'profit' : 'loss'">
                      ${{ scope.row.profit.toFixed(2) }}
                    </span>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'Trading',
  setup() {
    // 数据源选择
    const dataSources = [
      { value: 'coingecko', label: 'CoinGecko' },
      { value: 'binance', label: 'Binance' },
      { value: 'cryptocompare', label: 'CryptoCompare' }
    ]
    const selectedDataSource = ref('coingecko')
    const isLoading = ref(false)
    const lastUpdated = ref(new Date().toLocaleString())
    const autoRefresh = ref(true)
    const refreshInterval = ref(null)
    
    // 多数据源比较数据
    const comparisonData = reactive([
      { 
        symbol: 'BTC/USDT',
        coingecko: { price: '', change: 0 },
        binance: { price: '', change: 0 },
        cryptocompare: { price: '', change: 0 },
        priceDiff: 0
      },
      { 
        symbol: 'ETH/USDT',
        coingecko: { price: '', change: 0 },
        binance: { price: '', change: 0 },
        cryptocompare: { price: '', change: 0 },
        priceDiff: 0
      },
      { 
        symbol: 'BNB/USDT',
        coingecko: { price: '', change: 0 },
        binance: { price: '', change: 0 },
        cryptocompare: { price: '', change: 0 },
        priceDiff: 0
      },
      { 
        symbol: 'SOL/USDT',
        coingecko: { price: '', change: 0 },
        binance: { price: '', change: 0 },
        cryptocompare: { price: '', change: 0 },
        priceDiff: 0
      }
    ])
    
    // 计算价格差异
    const calculatePriceDiff = (symbol) => {
      const item = comparisonData.find(item => item.symbol === symbol)
      if (!item) return
      
      const prices = [
        parseFloat(item.coingecko.price.replace(/,/g, '')) || 0,
        parseFloat(item.binance.price.replace(/,/g, '')) || 0,
        parseFloat(item.cryptocompare.price.replace(/,/g, '')) || 0
      ].filter(price => price > 0)
      
      if (prices.length < 2) {
        item.priceDiff = 0
        return
      }
      
      const maxPrice = Math.max(...prices)
      const minPrice = Math.min(...prices)
      item.priceDiff = ((maxPrice - minPrice) / minPrice) * 100
    }
    
    // 获取所有数据源的数据
    const fetchAllDataSources = async () => {
      try {
        isLoading.value = true
        // 并行获取所有三个数据源的数据
        await Promise.all([
          fetchCoinGeckoData(false),
          fetchBinanceData(false),
          fetchCryptoCompareData(false)
        ])
        
        // 计算所有交易对的价格差异
        comparisonData.forEach(item => calculatePriceDiff(item.symbol))
        
        lastUpdated.value = new Date().toLocaleString()
        ElMessage({
          message: '所有数据源更新成功',
          type: 'success'
        })
      } catch (error) {
        console.error('更新数据源失败:', error)
        ElMessage({
          message: '部分数据源更新失败，请稍后重试',
          type: 'warning'
        })
      } finally {
        isLoading.value = false
      }
    }
    
    // 启动自动刷新
    const startAutoRefresh = () => {
      if (refreshInterval.value) clearInterval(refreshInterval.value)
      refreshInterval.value = setInterval(() => {
        fetchAllDataSources() // 每分钟刷新所有三个数据源的数据
      }, 60000) // 60秒
    }
    
    // 停止自动刷新
    const stopAutoRefresh = () => {
      if (refreshInterval.value) {
        clearInterval(refreshInterval.value)
        refreshInterval.value = null
      }
    }
    
    // 切换自动刷新状态
    const toggleAutoRefresh = () => {
      if (autoRefresh.value) {
        startAutoRefresh()
      } else {
        stopAutoRefresh()
      }
    }
    
    // 市场概览数据
    const marketOverview = reactive([
      { name: 'BTC/USDT', price: '加载中...', change: 0 },
      { name: 'ETH/USDT', price: '加载中...', change: 0 },
      { name: 'BNB/USDT', price: '加载中...', change: 0 },
      { name: 'SOL/USDT', price: '加载中...', change: 0 }
    ])
    
    // 获取CoinGecko数据
    const fetchCoinGeckoData = async (showMessage = true) => {
      try {
        isLoading.value = true
        const response = await axios.get('https://api.coingecko.com/api/v3/simple/price', {
          params: {
            ids: 'bitcoin,ethereum,binancecoin,solana',
            vs_currencies: 'usd',
            include_24hr_change: 'true'
          }
        })
        
        const data = response.data
        
        // 更新市场概览数据
        marketOverview[0].price = data.bitcoin.usd.toLocaleString()
        marketOverview[0].change = parseFloat(data.bitcoin.usd_24h_change.toFixed(2))
        
        marketOverview[1].price = data.ethereum.usd.toLocaleString()
        marketOverview[1].change = parseFloat(data.ethereum.usd_24h_change.toFixed(2))
        
        marketOverview[2].price = data.binancecoin.usd.toLocaleString()
        marketOverview[2].change = parseFloat(data.binancecoin.usd_24h_change.toFixed(2))
        
        marketOverview[3].price = data.solana.usd.toLocaleString()
        marketOverview[3].change = parseFloat(data.solana.usd_24h_change.toFixed(2))
        
        // 更新比较数据
        comparisonData[0].coingecko.price = data.bitcoin.usd.toLocaleString()
        comparisonData[0].coingecko.change = parseFloat(data.bitcoin.usd_24h_change.toFixed(2))
        
        comparisonData[1].coingecko.price = data.ethereum.usd.toLocaleString()
        comparisonData[1].coingecko.change = parseFloat(data.ethereum.usd_24h_change.toFixed(2))
        
        comparisonData[2].coingecko.price = data.binancecoin.usd.toLocaleString()
        comparisonData[2].coingecko.change = parseFloat(data.binancecoin.usd_24h_change.toFixed(2))
        
        comparisonData[3].coingecko.price = data.solana.usd.toLocaleString()
        comparisonData[3].coingecko.change = parseFloat(data.solana.usd_24h_change.toFixed(2))
        
        // 计算价格差异
        comparisonData.forEach(item => calculatePriceDiff(item.symbol))
        
        // 更新K线图表数据，仅当当前选中的数据源是CoinGecko时
        if (selectedDataSource.value === 'coingecko') {
          updateChartData(data)
        }
        
        if (showMessage) {
          lastUpdated.value = new Date().toLocaleString()
          ElMessage({
            message: 'CoinGecko数据更新成功',
            type: 'success'
          })
        }
      } catch (error) {
        console.error('获取CoinGecko数据失败:', error)
        ElMessage({
          message: '获取CoinGecko数据失败，请稍后重试',
          type: 'error'
        })
      } finally {
        isLoading.value = false
      }
    }
    
    // 获取Binance数据
    const fetchBinanceData = async (showMessage = true) => {
      try {
        isLoading.value = true
        
        // 并行请求多个交易对数据
        const [btcResponse, ethResponse, bnbResponse, solResponse] = await Promise.all([
          axios.get('https://api.binance.com/api/v3/ticker/24hr?symbol=BTCUSDT'),
          axios.get('https://api.binance.com/api/v3/ticker/24hr?symbol=ETHUSDT'),
          axios.get('https://api.binance.com/api/v3/ticker/24hr?symbol=BNBUSDT'),
          axios.get('https://api.binance.com/api/v3/ticker/24hr?symbol=SOLUSDT')
        ])
        
        // 更新市场概览数据
        marketOverview[0].price = parseFloat(btcResponse.data.lastPrice).toLocaleString()
        marketOverview[0].change = parseFloat(btcResponse.data.priceChangePercent)
        
        marketOverview[1].price = parseFloat(ethResponse.data.lastPrice).toLocaleString()
        marketOverview[1].change = parseFloat(ethResponse.data.priceChangePercent)
        
        marketOverview[2].price = parseFloat(bnbResponse.data.lastPrice).toLocaleString()
        marketOverview[2].change = parseFloat(bnbResponse.data.priceChangePercent)
        
        marketOverview[3].price = parseFloat(solResponse.data.lastPrice).toLocaleString()
        marketOverview[3].change = parseFloat(solResponse.data.priceChangePercent)
        
        // 更新比较数据
        comparisonData[0].binance.price = parseFloat(btcResponse.data.lastPrice).toLocaleString()
        comparisonData[0].binance.change = parseFloat(btcResponse.data.priceChangePercent)
        
        comparisonData[1].binance.price = parseFloat(ethResponse.data.lastPrice).toLocaleString()
        comparisonData[1].binance.change = parseFloat(ethResponse.data.priceChangePercent)
        
        comparisonData[2].binance.price = parseFloat(bnbResponse.data.lastPrice).toLocaleString()
        comparisonData[2].binance.change = parseFloat(bnbResponse.data.priceChangePercent)
        
        comparisonData[3].binance.price = parseFloat(solResponse.data.lastPrice).toLocaleString()
        comparisonData[3].binance.change = parseFloat(solResponse.data.priceChangePercent)
        
        // 计算价格差异
        comparisonData.forEach(item => calculatePriceDiff(item.symbol))
        
        // 获取K线数据
        const klineResponse = await axios.get('https://api.binance.com/api/v3/klines', {
          params: {
            symbol: 'BTCUSDT',
            interval: '1d',
            limit: 100
          }
        })
        
        // 更新K线图表，仅当当前选中的数据源是Binance时
        if (selectedDataSource.value === 'binance') {
          updateChartWithBinanceData(klineResponse.data)
        }
        
        if (showMessage) {
          lastUpdated.value = new Date().toLocaleString()
          ElMessage({
            message: 'Binance数据更新成功',
            type: 'success'
          })
        }
      } catch (error) {
        console.error('获取Binance数据失败:', error)
        ElMessage({
          message: '获取Binance数据失败，请稍后重试',
          type: 'error'
        })
      } finally {
        isLoading.value = false
      }
    }
    
    // 获取CryptoCompare数据
    const fetchCryptoCompareData = async (showMessage = true) => {
      try {
        isLoading.value = true
        
        // 获取多个币种的价格数据
        const priceResponse = await axios.get('https://min-api.cryptocompare.com/data/pricemultifull', {
          params: {
            fsyms: 'BTC,ETH,BNB,SOL',
            tsyms: 'USD'
          }
        })
        
        const data = priceResponse.data.RAW
        
        // 更新市场概览数据
        marketOverview[0].price = data.BTC.USD.PRICE.toLocaleString()
        marketOverview[0].change = parseFloat(data.BTC.USD.CHANGEPCT24HOUR.toFixed(2))
        
        marketOverview[1].price = data.ETH.USD.PRICE.toLocaleString()
        marketOverview[1].change = parseFloat(data.ETH.USD.CHANGEPCT24HOUR.toFixed(2))
        
        marketOverview[2].price = data.BNB.USD.PRICE.toLocaleString()
        marketOverview[2].change = parseFloat(data.BNB.USD.CHANGEPCT24HOUR.toFixed(2))
        
        marketOverview[3].price = data.SOL.USD.PRICE.toLocaleString()
        marketOverview[3].change = parseFloat(data.SOL.USD.CHANGEPCT24HOUR.toFixed(2))
        
        // 更新比较数据
        comparisonData[0].cryptocompare.price = data.BTC.USD.PRICE.toLocaleString()
        comparisonData[0].cryptocompare.change = parseFloat(data.BTC.USD.CHANGEPCT24HOUR.toFixed(2))
        
        comparisonData[1].cryptocompare.price = data.ETH.USD.PRICE.toLocaleString()
        comparisonData[1].cryptocompare.change = parseFloat(data.ETH.USD.CHANGEPCT24HOUR.toFixed(2))
        
        comparisonData[2].cryptocompare.price = data.BNB.USD.PRICE.toLocaleString()
        comparisonData[2].cryptocompare.change = parseFloat(data.BNB.USD.CHANGEPCT24HOUR.toFixed(2))
        
        comparisonData[3].cryptocompare.price = data.SOL.USD.PRICE.toLocaleString()
        comparisonData[3].cryptocompare.change = parseFloat(data.SOL.USD.CHANGEPCT24HOUR.toFixed(2))
        
        // 计算价格差异
        comparisonData.forEach(item => calculatePriceDiff(item.symbol))
        
        // 获取历史K线数据
        const historyResponse = await axios.get('https://min-api.cryptocompare.com/data/v2/histoday', {
          params: {
            fsym: 'BTC',
            tsym: 'USD',
            limit: 100
          }
        })
        
        // 更新K线图表，仅当当前选中的数据源是CryptoCompare时
        if (selectedDataSource.value === 'cryptocompare') {
          updateChartWithCryptoCompareData(historyResponse.data.Data.Data)
        }
        
        if (showMessage) {
          lastUpdated.value = new Date().toLocaleString()
          ElMessage({
            message: 'CryptoCompare数据更新成功',
            type: 'success'
          })
        }
      } catch (error) {
        console.error('获取CryptoCompare数据失败:', error)
        ElMessage({
          message: '获取CryptoCompare数据失败，请稍后重试',
          type: 'error'
        })
      } finally {
        isLoading.value = false
      }
    }
    
    // 根据选择的数据源获取数据
    const fetchDataBySource = () => {
      switch (selectedDataSource.value) {
        case 'coingecko':
          fetchCoinGeckoData()
          break
        case 'binance':
          fetchBinanceData()
          break
        case 'cryptocompare':
          fetchCryptoCompareData()
          break
      }
    }

    // 交易对选择
    const symbols = [
      { value: 'BTC/USDT', label: 'BTC/USDT' },
      { value: 'ETH/USDT', label: 'ETH/USDT' },
      { value: 'BNB/USDT', label: 'BNB/USDT' },
      { value: 'SOL/USDT', label: 'SOL/USDT' }
    ]
    const selectedSymbol = ref('BTC/USDT')
    
    // Binance 图表相关
    const binanceSymbol = ref('BTCUSDT')
    const binanceWebview = ref(null)
    
    // 更新 Binance 图表
    const updateBinanceChart = (newSymbol) => {
      binanceSymbol.value = newSymbol
      if (binanceWebview.value) {
        binanceWebview.value.src = `https://www.binance.com/zh-CN/trade/${newSymbol}?theme=dark&type=spot`
      }
    }

    // 交易表单
    const tradeForm = reactive({
      type: 'buy',
      orderType: 'limit',
      price: '45678.21',
      amount: '0.1'
    })

    // 计算总额
    const totalAmount = computed(() => {
      return (parseFloat(tradeForm.price) * parseFloat(tradeForm.amount)).toFixed(2)
    })

    // 资产数据
    const assets = reactive([
      { name: 'Bitcoin', symbol: 'BTC', balance: '0.5', value: '22,839.11' },
      { name: 'Ethereum', symbol: 'ETH', balance: '2.0', value: '6,491.34' },
      { name: 'Tether', symbol: 'USDT', balance: '1,000.00', value: '1,000.00' }
    ])

    // 订单数据
    const orders = reactive([
      { symbol: 'BTC/USDT', type: 'buy', price: '44,500.00', amount: '0.2' },
      { symbol: 'ETH/USDT', type: 'sell', price: '3,300.00', amount: '1.5' }
    ])

    // 交易历史
    const tradeHistory = reactive([
      { time: '2023-06-15 14:32:45', symbol: 'BTC/USDT', type: 'buy', price: '45,200.00', amount: '0.1', total: '4,520.00', status: 'completed' },
      { time: '2023-06-14 09:15:22', symbol: 'ETH/USDT', type: 'sell', price: '3,150.00', amount: '2.0', total: '6,300.00', status: 'completed' },
      { time: '2023-06-13 16:45:30', symbol: 'BTC/USDT', type: 'buy', price: '44,800.00', amount: '0.15', total: '6,720.00', status: 'completed' }
    ])

    // 图表实例
    let chartInstance = null
    const tradingChart = ref(null)

    // 更新图表数据 - CoinGecko
    const updateChartData = (data) => {
      if (!chartInstance) return
      
      // 由于CoinGecko API不直接提供K线数据，我们使用模拟数据
      // 但使用实际价格作为基准
      const basePrice = data.bitcoin.usd
      const klineData = generateKLineData(basePrice)
      
      const option = {
        title: {
          text: `BTC/USDT - 数据来源: CoinGecko`,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '10%',
          right: '10%',
          bottom: '15%'
        },
        xAxis: {
          type: 'category',
          data: klineData.map(item => item[0]),
          scale: true,
          boundaryGap: false,
          axisLine: { onZero: false },
          splitLine: { show: false },
          splitNumber: 20
        },
        yAxis: {
          scale: true,
          splitLine: { show: true },
        },
        dataZoom: [
          {
            type: 'inside',
            start: 50,
            end: 100
          },
          {
            show: true,
            type: 'slider',
            bottom: '5%',
            start: 50,
            end: 100
          }
        ],
        series: [
          {
            name: 'BTC/USDT',
            type: 'candlestick',
            data: klineData.map(item => item.slice(1)),
            itemStyle: {
              color: '#ef232a',
              color0: '#14b143',
              borderColor: '#ef232a',
              borderColor0: '#14b143'
            }
          }
        ]
      }
      
      chartInstance.setOption(option, true)
    }
    
    // 更新图表数据 - Binance
    const updateChartWithBinanceData = (klineData) => {
      if (!chartInstance) return
      
      // Binance K线数据格式转换
      // [开盘时间, 开盘价, 最高价, 最低价, 收盘价, 成交量, 收盘时间, ...]
      const formattedData = klineData.map(item => {
        const date = new Date(item[0])
        return [
          date.toISOString().split('T')[0],
          parseFloat(item[1]), // 开盘价
          parseFloat(item[4]), // 收盘价
          parseFloat(item[3]), // 最低价
          parseFloat(item[2])  // 最高价
        ]
      })
      
      const option = {
        title: {
          text: `BTC/USDT - 数据来源: Binance`,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '10%',
          right: '10%',
          bottom: '15%'
        },
        xAxis: {
          type: 'category',
          data: formattedData.map(item => item[0]),
          scale: true,
          boundaryGap: false,
          axisLine: { onZero: false },
          splitLine: { show: false },
          splitNumber: 20
        },
        yAxis: {
          scale: true,
          splitLine: { show: true }
        },
        dataZoom: [
          {
            type: 'inside',
            start: 50,
            end: 100
          },
          {
            show: true,
            type: 'slider',
            bottom: '5%',
            start: 50,
            end: 100
          }
        ],
        series: [
          {
            name: 'BTC/USDT',
            type: 'candlestick',
            data: formattedData.map(item => item.slice(1)),
            itemStyle: {
              color: '#ef232a',
              color0: '#14b143',
              borderColor: '#ef232a',
              borderColor0: '#14b143'
            }
          }
        ]
      }
      
      chartInstance.setOption(option, true)
    }
    
    // 更新图表数据 - CryptoCompare
    const updateChartWithCryptoCompareData = (historyData) => {
      if (!chartInstance) return
      
      // CryptoCompare数据格式转换
      const formattedData = historyData.map(item => {
        const date = new Date(item.time * 1000)
        return [
          date.toISOString().split('T')[0],
          item.open,
          item.close,
          item.low,
          item.high
        ]
      })
      
      const option = {
        title: {
          text: `BTC/USDT - 数据来源: CryptoCompare`,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '10%',
          right: '10%',
          bottom: '15%'
        },
        xAxis: {
          type: 'category',
          data: formattedData.map(item => item[0]),
          scale: true,
          boundaryGap: false,
          axisLine: { onZero: false },
          splitLine: { show: false },
          splitNumber: 20
        },
        yAxis: {
          scale: true,
          splitLine: { show: true }
        },
        dataZoom: [
          {
            type: 'inside',
            start: 50,
            end: 100
          },
          {
            show: true,
            type: 'slider',
            bottom: '5%',
            start: 50,
            end: 100
          }
        ],
        series: [
          {
            name: 'BTC/USDT',
            type: 'candlestick',
            data: formattedData.map(item => item.slice(1)),
            itemStyle: {
              color: '#ef232a',
              color0: '#14b143',
              borderColor: '#ef232a',
              borderColor0: '#14b143'
            }
          }
        ]
      }
      
      chartInstance.setOption(option, true)
    }
    
    // 初始化图表
    const initChart = () => {
      if (tradingChart.value) {
        chartInstance = echarts.init(tradingChart.value)
        
        // 响应窗口大小变化
        window.addEventListener('resize', () => {
          chartInstance.resize()
        })
        
        // 加载初始数据
        fetchDataBySource()
      }
    }
    
    // 生成模拟K线数据
    const generateKLineData = () => {
      const basePrice = 45000
      const data = []
      const today = new Date()
      
      for (let i = 0; i < 100; i++) {
        const date = new Date(today)
        date.setDate(date.getDate() - (100 - i))
        const dateStr = date.toISOString().split('T')[0]
        
        const open = basePrice + Math.random() * 2000 - 1000
        const close = open + Math.random() * 1000 - 500
        const low = Math.min(open, close) - Math.random() * 500
        const high = Math.max(open, close) + Math.random() * 500
        
        data.push([dateStr, open, close, low, high])
      }
      
      return data
    }
    
    // 提交交易
    const submitTrade = () => {
      const now = new Date()
      const timeStr = now.toLocaleString()
      
      // 添加到交易历史
      tradeHistory.unshift({
        time: timeStr,
        symbol: selectedSymbol.value,
        type: tradeForm.type,
        price: tradeForm.price,
        amount: tradeForm.amount,
        total: totalAmount.value,
        status: 'completed'
      })
      
      // 更新资产（简化处理）
      if (tradeForm.type === 'buy') {
        const btcAsset = assets.find(a => a.symbol === 'BTC')
        if (btcAsset) {
          btcAsset.balance = (parseFloat(btcAsset.balance) + parseFloat(tradeForm.amount)).toFixed(2)
        }
      } else {
        const btcAsset = assets.find(a => a.symbol === 'BTC')
        if (btcAsset) {
          btcAsset.balance = (parseFloat(btcAsset.balance) - parseFloat(tradeForm.amount)).toFixed(2)
        }
      }
      
      // 显示成功消息
      ElMessage({
        message: `${tradeForm.type === 'buy' ? '买入' : '卖出'}订单已成功执行`,
        type: 'success'
      })
    }
    
    // 取消订单
    const cancelOrder = (order) => {
      const index = orders.indexOf(order)
      if (index !== -1) {
        orders.splice(index, 1)
        ElMessage({
          message: '订单已取消',
          type: 'success'
        })
      }
    }
    
    onMounted(() => {
      // 首次加载时获取所有数据源的数据
      fetchAllDataSources()
      // 启动自动刷新
      startAutoRefresh()
    })
    
    onUnmounted(() => {
      stopAutoRefresh()
    })
    
    // 回测相关变量
    const backtestSettings = reactive({
      symbol: 'BTC/USDT',
      period: '30d',
      interval: '1d',
      strategyType: 'ma_cross',
      initialCapital: 10000,
      tradeAmount: 20,
      fastMAPeriod: 9,
      slowMAPeriod: 21,
      rsiPeriod: 14,
      overbought: 70,
      oversold: 30,
      bbPeriod: 20,
      bbStdDev: 2,
      customStrategy: '',
      stopLoss: 5,
      takeProfit: 10
    })
    
    const isBacktesting = ref(false)
    const backtestResults = ref([])
    const backtestTrades = ref([])
    const backtestSummary = reactive({
      totalReturn: 0,
      annualReturn: 0,
      sharpeRatio: 0,
      maxDrawdown: 0,
      winRate: 0,
      totalTrades: 0
    })
    const backtestChart = ref(null)
    const backtestChartInstance = ref(null)
    
    // 运行回测
    const runBacktest = async () => {
      try {
        isBacktesting.value = true
        backtestResults.value = []
        backtestTrades.value = []
        
        // 重置回测摘要
        Object.assign(backtestSummary, {
          totalReturn: 0,
          annualReturn: 0,
          sharpeRatio: 0,
          maxDrawdown: 0,
          winRate: 0,
          totalTrades: 0
        })
        
        // 模拟获取历史数据
        const historicalData = await fetchHistoricalData(backtestSettings.symbol, backtestSettings.period, backtestSettings.interval)
        
        // 验证数据有效性
        if (!historicalData || historicalData.length === 0) {
          throw new Error('获取历史数据失败，请检查网络连接或数据源')
        }
        
        // 根据策略类型执行回测
        let results
        switch (backtestSettings.strategyType) {
          case 'ma_cross':
            results = runMACrossStrategy(historicalData)
            break
          case 'rsi':
            results = runRSIStrategy(historicalData)
            break
          case 'bollinger':
            results = runBollingerStrategy(historicalData)
            break
          case 'custom':
            results = runCustomStrategy(historicalData)
            break
          default:
            throw new Error('未知的策略类型')
        }
        
        // 验证回测结果
        if (!results || !results.equityCurve || results.equityCurve.length === 0) {
          throw new Error('回测未产生有效结果，请检查策略参数')
        }
        
        backtestResults.value = results
        backtestTrades.value = results.trades || []
        
        // 计算回测结果
        calculateBacktestResults()
        
        // 绘制回测图表
        drawBacktestChart(results)
        
        ElMessage({
          message: '回测完成',
          type: 'success'
        })
      } catch (error) {
        console.error('回测失败:', error)
        ElMessage({
          message: '回测失败: ' + error.message,
          type: 'error',
          duration: 5000
        })
      } finally {
        isBacktesting.value = false
      }
    }
    
    // 获取历史数据
    const fetchHistoricalData = async (symbol, period, interval) => {
      // 这里应该是实际的API调用，我们使用模拟数据
      return generateMockHistoricalData(symbol, period, interval)
    }
    
    // 生成模拟历史数据
    const generateMockHistoricalData = (symbol, period, interval) => {
      const data = []
      const now = new Date()
      let days = 30
      
      if (period === '7d') days = 7
      else if (period === '30d') days = 30
      else if (period === '90d') days = 90
      else if (period === '1y') days = 365
      
      const basePrice = symbol === 'BTC/USDT' ? 45000 : 
                       symbol === 'ETH/USDT' ? 3000 : 
                       symbol === 'BNB/USDT' ? 400 : 150
      
      for (let i = 0; i < days; i++) {
        const date = new Date(now)
        date.setDate(date.getDate() - (days - i))
        
        const open = basePrice + Math.random() * 2000 - 1000
        const close = open + Math.random() * 1000 - 500
        const high = Math.max(open, close) + Math.random() * 500
        const low = Math.min(open, close) - Math.random() * 500
        const volume = Math.random() * 1000 + 500
        
        data.push({
          date: date.toISOString().split('T')[0],
          open,
          high,
          low,
          close,
          volume
        })
      }
      
      return data
    }
    
    // MA交叉策略
    const runMACrossStrategy = (data) => {
      const results = {
        equityCurve: [],
        trades: []
      }
      
      const fastMA = backtestSettings.fastMAPeriod
      const slowMA = backtestSettings.slowMAPeriod
      const capital = backtestSettings.initialCapital
      const tradePercent = backtestSettings.tradeAmount / 100
      const stopLoss = backtestSettings.stopLoss / 100
      const takeProfit = backtestSettings.takeProfit / 100
      
      let position = 0
      let equity = capital
      let lastBuyPrice = 0
      
      // 计算MA
      const fastMAs = calculateMA(data, fastMA)
      const slowMAs = calculateMA(data, slowMA)
      
      for (let i = slowMA; i < data.length; i++) {
        const currentPrice = data[i].close
        const currentDate = data[i].date
        
        // 检查交易信号
        const buySignal = fastMAs[i] > slowMAs[i] && fastMAs[i-1] <= slowMAs[i-1]
        const sellSignal = fastMAs[i] < slowMAs[i] && fastMAs[i-1] >= slowMAs[i-1]
        
        // 检查止损止盈
        const stopLossTriggered = position > 0 && currentPrice <= lastBuyPrice * (1 - stopLoss)
        const takeProfitTriggered = position > 0 && currentPrice >= lastBuyPrice * (1 + takeProfit)
        
        if (buySignal && position === 0) {
          // 买入
          const tradeValue = equity * tradePercent
          const amount = tradeValue / currentPrice
          position = amount
          lastBuyPrice = currentPrice
          
          results.trades.push({
            date: currentDate,
            type: 'buy',
            price: currentPrice,
            amount,
            value: tradeValue
          })
        } else if ((sellSignal || stopLossTriggered || takeProfitTriggered) && position > 0) {
          // 卖出
          const tradeValue = position * currentPrice
          const profit = tradeValue - (position * lastBuyPrice)
          equity += profit
          position = 0
          
          results.trades.push({
            date: currentDate,
            type: 'sell',
            price: currentPrice,
            amount: position,
            value: tradeValue,
            profit
          })
        }
        
        // 更新权益曲线
        results.equityCurve.push({
          date: currentDate,
          equity: equity + (position * currentPrice)
        })
      }
      
      return results
    }
    
    // 计算移动平均线
    const calculateMA = (data, period) => {
      const ma = []
      for (let i = period - 1; i < data.length; i++) {
        let sum = 0
        for (let j = 0; j < period; j++) {
          sum += data[i - j].close
        }
        ma.push(sum / period)
      }
      return ma
    }
    
    // RSI策略
    const runRSIStrategy = (data) => {
      // 实现类似MA策略的逻辑，但使用RSI指标
      return {
        equityCurve: [],
        trades: []
      }
    }
    
    // 布林带策略
    const runBollingerStrategy = (data) => {
      // 实现类似MA策略的逻辑，但使用布林带指标
      return {
        equityCurve: [],
        trades: []
      }
    }
    
    // 自定义策略
    const runCustomStrategy = (data) => {
      // 这里可以执行用户自定义的策略代码
      return {
        equityCurve: [],
        trades: []
      }
    }
    
    // 计算回测结果
    const calculateBacktestResults = () => {
      if (!backtestResults.value.equityCurve.length) return
      
      const equityCurve = backtestResults.value.equityCurve
      const trades = backtestResults.value.trades
      
      // 计算总收益率
      const initialEquity = equityCurve[0].equity
      const finalEquity = equityCurve[equityCurve.length - 1].equity
      backtestSummary.totalReturn = ((finalEquity - initialEquity) / initialEquity) * 100
      
      // 计算年化收益率
      const days = equityCurve.length
      const years = days / 365
      backtestSummary.annualReturn = (Math.pow(1 + backtestSummary.totalReturn / 100, 1 / years) - 1) * 100
      
      // 计算夏普比率
      const returns = []
      for (let i = 1; i < equityCurve.length; i++) {
        const ret = (equityCurve[i].equity - equityCurve[i - 1].equity) / equityCurve[i - 1].equity
        returns.push(ret)
      }
      
      const avgReturn = returns.reduce((a, b) => a + b, 0) / returns.length
      const stdDev = Math.sqrt(returns.map(x => Math.pow(x - avgReturn, 2)).reduce((a, b) => a + b, 0) / returns.length)
      backtestSummary.sharpeRatio = stdDev === 0 ? 0 : avgReturn / stdDev
      
      // 计算最大回撤
      let peak = initialEquity
      let maxDrawdown = 0
      
      for (const item of equityCurve) {
        if (item.equity > peak) peak = item.equity
        const drawdown = (peak - item.equity) / peak
        if (drawdown > maxDrawdown) maxDrawdown = drawdown
      }
      
      backtestSummary.maxDrawdown = maxDrawdown * 100
      
      // 计算胜率
      const profitableTrades = trades.filter(t => t.profit > 0).length
      backtestSummary.totalTrades = trades.length
      backtestSummary.winRate = backtestSummary.totalTrades > 0 ? (profitableTrades / backtestSummary.totalTrades) * 100 : 0
    }
    
    // 绘制回测结果图表
    const drawBacktestChart = (results) => {
      // 确保DOM已加载
      nextTick(() => {
        if (!backtestChart.value) {
          console.error('图表容器未找到')
          return
        }
        
        // 销毁旧图表实例
        if (backtestChartInstance.value) {
          backtestChartInstance.value.dispose()
        }
      
      // 初始化图表
      backtestChartInstance.value = echarts.init(backtestChart.value)
      
      // 准备图表数据
      const chartDates = results.equityCurve.map(item => item.date)
      const chartEquityValues = results.equityCurve.map(item => item.equity)
      
      const option = {
        title: {
          text: '回测结果 - 权益曲线',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const date = params[0].axisValue
            const value = params[0].data.toFixed(2)
            return `${date}<br/>权益: $${value}`
          }
        },
        xAxis: {
          type: 'category',
          data: chartDates,
          scale: true,
          boundaryGap: false,
          axisLine: { onZero: false },
          splitLine: { show: false },
          axisLabel: {
            formatter: function(value) {
              return value.split(' ')[0] // 只显示日期部分
            }
          }
        },
        yAxis: {
          type: 'value',
          scale: true,
          splitLine: { show: true },
          axisLabel: {
            formatter: '${value}'
          }
        },
        grid: {
          left: '3%',
          right: '3%',
          bottom: '3%',
          containLabel: true
        },
        series: [
          {
            name: '权益',
            type: 'line',
            data: chartEquityValues,
            smooth: true,
            showSymbol: false,
            lineStyle: {
              width: 2,
              color: '#5470c6'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(84, 112, 198, 0.5)'
                },
                {
                  offset: 1,
                  color: 'rgba(84, 112, 198, 0.1)'
                }
              ])
            }
          }
        ]
      }
      
      backtestChartInstance.value.setOption(option)
      
      // 响应窗口大小变化
      window.addEventListener('resize', function() {
        backtestChartInstance.value.resize()
      })
    }
    
    // 保存策略
    const saveStrategy = () => {
      if (!backtestResults.value.length) {
        ElMessage({
          message: '请先运行回测',
          type: 'warning'
        })
        return
      }
      
      ElMessageBox.prompt('请输入策略名称', '保存策略', {
        confirmButtonText: '保存',
        cancelButtonText: '取消',
        inputPattern: /\S+/,
        inputErrorMessage: '策略名称不能为空'
      }).then(({ value }) => {
        // 保存策略到本地存储
        const savedStrategies = JSON.parse(localStorage.getItem('backtestStrategies') || '[]')
        
        const strategyToSave = {
          id: Date.now(),
          name: value,
          settings: { ...backtestSettings },
          summary: { ...backtestSummary },
          savedAt: new Date().toLocaleString()
        }
        
        savedStrategies.push(strategyToSave)
        localStorage.setItem('backtestStrategies', JSON.stringify(savedStrategies))
        
        ElMessage({
          message: `策略 "${value}" 已保存`,
          type: 'success'
        })
      }).catch(() => {
        // 取消保存
      })
    }
    
    // 加载策略
    const loadStrategy = () => {
      // 从本地存储获取已保存的策略
      const savedStrategies = JSON.parse(localStorage.getItem('backtestStrategies') || '[]')
      
      if (savedStrategies.length === 0) {
        ElMessage({
          message: '没有找到已保存的策略',
          type: 'info'
        })
        return
      }
      
      // 准备策略列表
      const options = savedStrategies.map(strategy => ({
        label: `${strategy.name} (${strategy.savedAt}) - 收益率: ${strategy.summary.totalReturn.toFixed(2)}%`,
        value: strategy.id
      }))
      
      // 显示策略选择对话框
      const strategyOptions = options.map(opt => `${opt.label}`).join('\n')
      ElMessageBox.confirm(
        `可用策略:\n${strategyOptions}\n\n请在控制台中输入要加载的策略序号(1-${options.length})`,
        '加载策略',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }
      ).then(() => {
        // 默认加载第一个策略
        const value = options[0].value
        // 查找选中的策略
        const selectedStrategy = savedStrategies.find(s => s.id === value)
        
        if (selectedStrategy) {
          // 加载策略设置
          Object.assign(backtestSettings, selectedStrategy.settings)
          
          ElMessage({
            message: `策略 "${selectedStrategy.name}" 已加载`,
            type: 'success'
          })
          
          // 清空当前回测结果
          backtestResults.value = []
          backtestTrades.value = []
          
          // 如果有图表实例，清除图表
          if (backtestChartInstance.value) {
            backtestChartInstance.value.clear()
          }
        }
      }).catch(() => {
        // 取消加载
      })
    }
    
    return {
      // 数据源相关
      dataSources,
      selectedDataSource,
      isLoading,
      lastUpdated,
      fetchDataBySource,
      fetchAllDataSources,
      autoRefresh,
      toggleAutoRefresh,
      
      // 市场数据
      marketOverview,
      symbols,
      selectedSymbol,
      binanceSymbol,
      binanceWebview,
      updateBinanceChart,
      
      // 比较数据
      comparisonData,
      
      // 交易相关
      tradeForm,
      totalAmount,
      assets,
      orders,
      tradeHistory,
      tradingChart,
      submitTrade,
      cancelOrder,
      
      // 回测相关
      backtestSettings,
      isBacktesting,
      backtestResults,
      backtestTrades,
      backtestSummary,
      backtestChart,
      runBacktest,
      saveStrategy,
      loadStrategy
    }
  }
}
</script>

<style scoped>
.trading-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.market-item {
  padding: 15px;
  border-radius: 8px;
  background-color: #f5f7fa;
  text-align: center;
  margin-bottom: 10px;
}

.market-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.market-price {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.market-change {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 5px;
}

.up {
  color: #14b143;
}

.down {
  color: #ef232a;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.trading-chart {
  width: 100%;
  height: 100%;
}

.binance-webview {
  width: 100%;
  height: 700px;
  border: none;
  display: inline-flex;
}

.buy-btn {
  background-color: #14b143;
  border-color: #14b143;
}

.sell-btn {
  background-color: #ef232a;
  border-color: #ef232a;
}

.asset-overview {
  padding: 10px 0;
}

.asset-item {
  text-align: center;
  margin-bottom: 10px;
}

.asset-label {
  font-size: 14px;
  color: #909399;
}

.asset-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.asset-detail {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 5px 0;
}

.asset-name {
  font-weight: bold;
}

.asset-balance {
  color: #606266;
}

.data-source-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.last-updated {
  font-size: 12px;
  color: #909399;
  margin-right: 10px;
}

.price-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.price-cell div:first-child {
  font-weight: bold;
  margin-bottom: 4px;
}

.price-diff .warning {
  color: #e6a23c;
  font-weight: bold;
}

.up {
  color: #14b143;
}

.down {
  color: #ef232a;
}
</style>